'use strict'

const { Exam, ExamLog } = require('../entity/myentity')

const { Service } = require('egg')

class examService extends Service {
  /**
   * 创建考试
   * @param {Exam} exam 考试对象
   * @param {number} u_id 创建者的id
   */
  async create(exam, u_id) {
    const { app, ctx } = this
    const conn = await app.mysql.beginTransaction()
    const time = ctx.helper.parseTime(new Date())
    try {
      // 验证用户是不是该班级的老师
      const queryTeacher = await conn.get('u_class', {
        c_id: exam.c_id,
        u_id: u_id,
        isTeacher: true
      })
      if (queryTeacher == null) {
        await conn.rollback()
        ctx.logger.error(`用户${u_id}不是班级${exam.c_id}的老师，拒绝插入数据`)
        return { suc: false, msg: '只有班级的老师可以创建考试哦' }
      }
      // 验证考试名
      const queryName = await conn.get('exam', { name: exam.name })
      if (queryName != null) {
        await conn.rollback()
        ctx.logger.error(`考试名${exam.name}已存在，拒绝插入数据`)
        return { suc: false, msg: '该考试名已存在' }
      }
      exam.create_time = time
      const createExam = await conn.insert('exam', exam)
      // 创建log
      const log = new ExamLog(time, '创建了考试', createExam.insertId, u_id)
      await conn.insert('exam_log', log)
      // 查询刚刚的创建
      const queryResult = await conn.get('exam', { id: createExam.insertId })
      await conn.commit()
      ctx.logger.info(
        `用户${u_id}创建了考试${exam.name}，考试id${createExam.insertId}`
      )
      return { suc: true, data: queryResult, msg: '创建考试成功' }
    } catch (error) {
      let e = "examService.create()" +"：\n" + error;
      await conn.rollback();
      ctx.logger.error(e);
      return { suc: false, msg: e }
    }
  }

  /**
   * 修改考试信息，要求exam必须要有id
   * @param {Exam} exam
   */
  async update(exam){
    const {app,ctx} = this
    try {
      await app.mysql.update("exam",exam);
      return {suc:true,msg:"修改考试成功"}
    }catch (e) {
      ctx.logger.error(e)
      return {suc:false ,msg:e}
    }
  }

  /**
   * 删除一个考试
   * @param {number} id 待删除的考试对象id
   * @param {number} u_id 删除者的id
   */
  async del(id, u_id) {
    const { app, ctx } = this
    const conn = await app.mysql.beginTransaction()
    try {
      // 查找该考试
      const queryExam = await conn.get('exam', { id: id })
      if (queryExam == null) {
        ctx.logger.error(`没有找到考试${id}`)
        return { suc: false, msg: '没有该考试的数据' }
      }
      // 验证用户是不是该班级的老师
      const queryTeacher = await conn.get('u_class', {
        c_id: queryExam.c_id,
        u_id: u_id,
        isTeacher: true
      })
      if (queryTeacher == null) {
        ctx.logger.error(`用户${u_id}不是班级${id}的老师，拒绝删除数据`)
        return { suc: false, msg: '只有班级的老师可以删除考试' }
      }
      // 进行级联删除
      await conn.delete('exam', { id: id })
      await conn.commit()
      ctx.logger.info(`用户${u_id}删除了考试${id}`)
      return { suc: true, msg: '删除考试成功' }
    } catch (error) {
      ctx.logger.error(error)
      await conn.rollback()
      return { suc: false, msg: error }
    }
  }

  /**
   * 获取考试
   * @param {Exam} exam
   */
  async get(exam) {
    const { app, ctx } = this
    try {
      let res = await app.mysql.select('exam', { where: exam })
      ctx.logger.info(`批量查询考试${res}`)
      return { data: res, suc: true, msg: '查询考试成功' }
    } catch (error) {
      let e = "examService.get()" +"：\n" + error;
      ctx.logger.error(e)
      return { msg: e, suc: false }
    }
  }
  async getOne(exam) {
    const { app, ctx } = this
    try {
      let res = await app.mysql.get('exam', exam)
      ctx.logger.info(`查询考试${res.id}`)
      return { data: res, suc: true, msg: '查询考试成功' }
    } catch (error) {
      let e = "examService.getOne()" +"：\n" + error;
      ctx.logger.error(e)
      return { msg: e, suc: false }
    }
  }

  /**
   * 获取一个用户全部的考试
   * @param {number} u_id 用户id
   */
  async userGetAll(u_id) {
    const { app, ctx } = this
    const mysql = app.mysql
    try {
      let queryUserClass = await mysql.select('u_class', {
        where: { u_id: u_id }
      })
      if (queryUserClass == null) {
        ctx.log.info(`没有找到用户${u_id}的任何班级，跳过后续查询`)
        return { suc: true, msg: '查询用户全部考试成功', data: [] }
      }
      let userExamList = []
      for (let i in queryUserClass) {
        let c_id = queryUserClass[i].c_id
        let exams = (await this.get({ c_id: c_id })).data
        for (let j in exams) {
          userExamList.push(exams[j])
        }
      }
      ctx.logger.info(`查询用户${u_id}的全部考试`)
      return { suc: true, msg: '查询用户全部考试成功', data: userExamList }
    } catch (error) {
      ctx.logger.error(error)
      return { msg: error, suc: false }
    }
  }

  /**
   * 获取由某个用户管理的全部考试
   * @param {*} u_id
   */
  async userManageExam(u_id) {
    const {app, ctx} = this
    const mysql = app.mysql
    try {
      // 获取user管理的班级
      let queryUserClass = await mysql.select('u_class', {where: {u_id: u_id, isTeacher: true}})
      let userManageList = []
      for (let i in queryUserClass) {
        let uclass = queryUserClass[i]
        // let userManageClass = await mysql.get("my_class",uclass.c_id);
        // userManageList.push(userManageClass);\
        let uclassexam_list = await mysql.select('exam', {where: {c_id: uclass.c_id}})
        for (let j in uclassexam_list) {
          userManageList.push(uclassexam_list[j])
        }
      }
      ctx.logger.info(`查询用户${u_id}管理的全部考试`)
      return {suc: true, data: userManageList, msg: '查询用户管理的全部考试成功'}
    } catch (error) {
      ctx.logger.error(error)
      return { msg: error, suc: false }
    }
  }
}

module.exports = examService
